﻿using System;
using System.Collections.Generic;
using System.Web;

using System.Configuration;
using QuickDev.Common.Security;
using QuickDev.SSO;
using QuickDev.Common.Utils;

namespace QuickDev.Web.App
{
    public class WebServices
    {
        /// <summary>
        /// GetTicket
        /// </summary>
        /// <returns>ticket</returns>
        public static string GetTicket()
        {
            string ip = Strings.ToDelimitedList( Utility.DNSLookup( "localhost" ) , "|" );
            //string date = SsoCipher.Hash( DateTime.Today.ToUniversalTime().Ticks.ToString() );

            //string ip = "HostName,freecin-server.freecin.domain|Address,127.0.0.1";
            string date = SsoCipher.Hash( DateTime.Today.ToUniversalTime().Ticks.ToString() );

            return Encrypts.Encrypt( SsoCipher.EncryptVector( ConfigurationManager.AppSettings["APP_KEY"], ip, date ), PasswordType.MD5 );
        }

        /// <summary>
        /// TryParse
        /// </summary>
        /// <param name="tokenText">tokenText</param>
        /// <param name="token">token</param>
        /// <returns>bool successful</returns>
        public static bool TryParse( string xml, out string objXml )
        {
            string ip = Strings.ToDelimitedList( Utility.DNSLookup( "localhost" ) , "|" );
            //string date = SsoCipher.Hash( DateTime.Today.ToUniversalTime().Ticks.ToString() );

            //string ip = "HostName,freecin-server.freecin.domain|Address,127.0.0.1";
            string date = SsoCipher.Hash( DateTime.Today.ToUniversalTime().Ticks.ToString() );

            objXml = String.Empty;

            if ( string.IsNullOrEmpty( xml ) || xml.Equals( "InValid Ticket" ) )
                return false;

            string[] vector = null;

            if ( !SsoCipher.TryParseVector( xml, out vector ) )
                return false;
            if ( vector.Length != 3 )
                return false;
            if ( !String.Equals( ip, vector[1] ) )
                return false;
            if ( !String.Equals( date, vector[2] ) )
                return false;

            objXml = Encrypts.Decrypt( vector[0] ).Substring( 0, Encrypts.Decrypt( vector[0] ).LastIndexOf( ip ) );
            return true;
        }
    }
}
